package com.gill.service.impl;

import com.gill.service.ConsumerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class ConsumerServiceImpl implements ConsumerService {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoadBalancerClient eurekaClient;

    /**
     * rest方式的RPC，存在硬编码的问题
     * PS：需要删除RestConfig的@LoadBalanced注解
     */
    @Override
    public String sayHelloByRest(String message) {
//         准备工作
        String protocol = "http";
        String hostname = "localhost";
        int port = 8004;
        String uri = "/provider/sayhello?message="+message;

        // http://localhost:8004/provider/sayhello?message=hello
        String url = protocol + "://" + hostname + ":" +port + uri;

        // invoker provider test
        String result = restTemplate.getForObject(url, String.class);

        return result;
    }

    /**
     * 这个方式仅仅是说明eureka可以动态获取服务的信息，不需要硬编码
     * PS：需要删除RestConfig的@LoadBalanced注解
     */
    @Override
    public String sayHelloByEureka(String message) {
        ServiceInstance service = eurekaClient.choose("HELLO-SERVICE-PROVIDER");
        String protocol = "http";
        String hostname = service.getHost();//可以动态获取
        int port = service.getPort();//可以动态获取
        String uri = "/provider/sayhello?message="+message;
        String url = protocol + "://" + hostname + ":" +port + uri;
        String result = restTemplate.getForObject(url, String.class);
        return result;
    }

    /**
     * 测试负载均衡使用，与上边两个方法不能同时使用
     * PS：在RestConfig添加@LoadBalanced注解
     */
    public String sayHelloByLoadBalance(String message) {
        String uri = "/provider/sayhello?message="+message;
        // http://localhost:8005/provider/sayhello?message=hello
        String url = "http://hello-service-provider"+uri;
        String result = restTemplate.getForObject(url, String.class);

        return result;
    }
}
